#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash abinit-9.6.2.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1
if [[ "$1" == "$2" ]]; then echo "构建路径与安装路径不能相同，请输入正确的路径"; exit 1; fi

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
set -e

download_pkg()
{
    wget -t 40 -c $1 -O $buildpath/abinit-9.6.2.tar.gz
    tar xf $buildpath/abinit-9.6.2.tar.gz -C $buildpath
    #rm -rf $buildpath/abinit-9.6.2.tar.gz
}

#download_pkg https://www.abinit.org/sites/default/files/packages/abinit-9.6.2.tar.gz 
download_pkg https://github.com/abinit/abinit/archive/refs/tags/9.6.2.tar.gz
cd $buildpath/abinit-9.6.2
./autogen.sh
./configure CC=mpicc CXX=mpicxx FC="mpifort -fallow-argument-mismatch" --prefix=$installpath/abinit-9.6.2 --enable-openmp=yes --with-mpi=yes --enable-mpi-io=yes --with-linalg-flavor=openblas LINALG_LIBS="-L$installpath/openblas-0.3.21/lib -lopenblas -L$installpath/scalapack-2.2.0/lib -lscalapack" --with-fft-flavor=fftw3 FFTW3_LDFLAGS="-L$installpath/fftw-3.3.10/lib" FFTW3_CPPFLAGS="-I$installpath/fftw-3.3.10/include" FFTW3_LIBS="-lfftw3 -lfftw3_omp -lfftw3_mpi -lfftw3_threads -lfftw3f -lfftw3f_omp -lfftw3f_mpi -lfftw3f_threads" --with-hdf5=$installpath/hdf5-1.12.1 --with-netcdf=$installpath/netcdf-c-4.9.0 --with-netcdf-fortran=$installpath/netcdf-fortran-4.6.0 --with-libxc=$installpath/libxc-4.3.4 --enable-netcdf-default=no
make -j$(nproc)
make install

cat > "$installpath/abinit-9.6.2/abinit_modulefiles" <<EOF
#%Module1.0
conflict abinit
module purge
module use $installpath
module load ${installpath}/gcc-10.3.1-2022.11-aarch64-linux/gcc_modulefiles
module load ${installpath}/openmpi-4.1.2/openmpi_modulefiles
module load ${installpath}/openblas-0.3.21/openblas_modulefiles
module load ${installpath}/scalapack-2.2.0/scalapack_modulefiles
module load ${installpath}/libxc-4.3.4/libxc_modulefiles
module load ${installpath}/fftw-3.3.10/fftw_modulefiles
module load ${installpath}/hdf5-1.12.1/hdf5_modulefiles
module load ${installpath}/pnetcdf-1.12.3/pnetcdf_modulefiles
module load ${installpath}/netcdf-c-4.9.0/netcdf-c_modulefiles
module load ${installpath}/netcdf-fortran-4.6.0/netcdf-fortran_modulefiles

variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}

set abinit [getModulefileDir]
prepend-path PATH \$abinit/bin
prepend-path LD_LIBRARY_PATH \$abinit/lib

EOF

##rm -rf $buildpath/abinit-9.6.2
